"""
@name         top odn 一键回单
@version      1.0
@time         2025/05/13 09:19:36
@description  Retrieve data from top, curve ID is 130927587, automatically sorted, statiusName is non chargeback, 
              may include work order pool, processing is moderate, use order_no, fill in remark as 1 to achieve chargeback.
              Generate log files with date names Used to view operation records.
@author       liuYanXiang,652455342@qq.com
@match        https://133.96.90.208:9005/*
@Must-do      Reacquire the JSESSIONID and write it to the 7_Authorization.
              If you have a better alternative to JSESSIONID, such as session, change it!
"""

import requests
import json
from datetime import datetime
import time
import logging


now = datetime.now().strftime("%Y%m%d_%H%M%S")
log_filename = f"{now}.log"
logging.basicConfig(filename=log_filename, level=logging.INFO,
                    format='root@localhost %(asctime)s(%Y:%m:%d %H:%M:%S) >>> %(message)s',
                    datefmt='%Y:%m:%d %H:%M:%S')

def get_authorization():
    try:
        with open('7_Authorization', 'r') as file:
            for line in file:
                if line:
                    return line
    except FileNotFoundError:
        logging.info("7_Authorization file not found.")
    return None

def get_info_and_refund():
    authorization = get_authorization()
    url = "https://133.96.90.208:9005/cutover-api/odn/order/cityGrid/orderPage?pageNum=1&pageSize=50&orderType=ODN" 
    headers = {
            'accept': 'application/json, text/plain, */*',
            'accept-encoding': 'gzip, deflate, br, zstd',
            'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            'authorization': authorization,
            'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36'
        }
    data = {
        "cityCode": "",
        "areaCode": "",
        "beginTime": "",
        "endTime": "",
        "gridId": "130927587", 
        "orderStatus": "",
        "taskId": ""
    }

    try:
        logging.info("Start obtaining TOP page data.")
        response = requests.post(url, headers=headers, json=data, verify=False, timeout=10)
        if response.status_code == 200:
            logging.info("Data acquisition successful.")
            result = response.json()
            logging.info(result)
            num = 0
            for row in result["rows"]:
                order_no = row["orderNo"]
                type = row["type"]
                resource_name = row["resourceName"]
                task_id = row["taskId"]
                memo = row["memo"]
                statusName = row["statusName"]
                if statusName != "退单":
                    refund_url = "https://133.96.90.208:9005/cutover-api/odn/order/adminTuiDan"
                    refund_data = {
                        "status": -1, 
                        "orderNo": order_no,
                        "remark": "1"  
                    }
                    max_attempts = 3
                    for attempt in range(max_attempts):
                        try:
                            logging.info(f"{order_no} Start refunding.")
                            refund_response = requests.post(refund_url, headers=headers, json=refund_data, verify=False, timeout=10)
                            time.sleep(2)
                            refund_code = refund_response.json()["code"]
                            logging.info(refund_code)
                            if refund_code == 200:
                                logging.info(f"{order_no} Refund successful.")
                                num += 1
                                break
                        except (requests.RequestException, json.JSONDecodeError) as e:
                            if attempt < max_attempts - 1:
                                logging.info(f"{order_no} An error occurred in the request, please try {attempt + 2}: {e}.")
                            else:
                                logging.info(f"{order_no} Refund failed.")
            logging.info(f"Number of completed refunds {num}.")
        else:
            logging.info(f"Request failed, status code: {response.status_code}.")
    except requests.RequestException as e:
        logging.info(f"Request error occurred: {e}.")

if __name__ == "__main__":
    get_info_and_refund()